package chen.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.ehcache.CacheManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import chen.web.firewall.AccountFilter;
import chen.web.firewall.IpFilter;
import chen.web.firewall.UuidFilter;
import chen.web.install.InstalledFlag;
import chen.web.stat.StatisticsFilter;

public class MyFilter implements Filter {

	private static final Log log = LogFactory.getLog(DispatcherFilter.class);

	private static List<Filter> filterList = new ArrayList<Filter>();
	
	@Override
	public void destroy() {
		// TODO Auto-generated method stub
		for(Filter filter : filterList){
			filter.destroy();
		}
		SpringDispatcherInit.getDispatcherServlet().destroy();
		CacheManager.create().shutdown();
	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// TODO Auto-generated method stub
		HttpServletRequest request = (HttpServletRequest)req;
		HttpServletResponse response = (HttpServletResponse)res;
		
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		String servletPath = request.getServletPath();
		if(!filt(servletPath) || !InstalledFlag.installed()){
			chain.doFilter(req, res);
			return;
		}
		MyChain myChain = new MyChain(chain);
		myChain.doFilter(req, res);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {
		// TODO Auto-generated method stub
		filterList.add(new IpFilter());
		filterList.add(new InitMyContextFilter());
		filterList.add(new UuidFilter());
		filterList.add(new AccountFilter());
		filterList.add(new StatisticsFilter());
		filterList.add(new DispatcherFilter());

		for(Filter filter : filterList){
			filter.init(config);
		}
		if(InstalledFlag.installed()){
			log.debug("初始化spring");
			SpringDispatcherInit.init(config.getServletContext());	
		} else {
			log.warn("没有初始化spring，因为系统未安装");
		}
	}
	
	public static class MyChain implements FilterChain{
		private int index = -1;
		private FilterChain chain;
		public MyChain(FilterChain chain){
			this.chain = chain;
		}
		@Override
		public void doFilter(ServletRequest req, ServletResponse res)
				throws IOException, ServletException {
			// TODO Auto-generated method stub
			++ index;
			if(index == filterList.size()){
				chain.doFilter(req, res);
				return;
			}
			filterList.get(index).doFilter(req, res, this);	
		}
		
	}
	
	/**
	 * 是否过滤
	 * @param servletPath
	 * @return
	 */
	private boolean filt(String servletPath){
		int i = servletPath.lastIndexOf('.');
		if(i == -1){
			return true;
		}
		if(i < servletPath.length()-1){
			String suffix = servletPath.substring(i+1);
			return suffixes.contains(suffix);
		}
		return false;
	}
	
	/** 后缀 */
	private static Set<String> suffixes = new HashSet<String>();
	
	public void setSuffixs(Set<String> suffixes){
		MyFilter.suffixes = suffixes;
	}
	
	public static Set<String> getSuffixs(){
		return suffixes;
	}
	
	public static <T extends Filter> T getFilter(Class<T> cls){
		for(Filter filter : filterList){
			if(filter.getClass().equals(cls)){
				return cls.cast(filter);
			}
		}
		return null;
	}

}
